<template>
  <view class="container">


    <!-- 原始商品 -->
    <view class="section">
      <text class="section-title">订单商品</text>
      <view
        v-for="(item, idx) in originalList"
        :key="item.id || idx"
        class="card"
      >
        <image :src="item.image" class="product-img" />
        <view class="info">
          <text class="name">{{ item.productName }}</text>
          <text class="spec">{{ item.sku }}</text>
          <text class="price">￥{{ item.price }}</text>
        </view>
        <view class="counter">
          <button
            @click="changeCount('original', idx, -1)"
            :disabled="item.count == 0"
          >
            -
          </button>
          <text>{{ item.count }}</text>
          <button
            @click="changeCount('original', idx, 1)"
            :disabled="item.count >= item.number"
          >
            +
          </button>
        </view>
      </view>
    </view>

    <!-- 补充商品 -->
    <view class="section">
      <text class="section-title">补充商品</text>
      <view v-for="(item, idx) in addList" :key="item.id || idx" class="card">
        <image :src="item.image" class="product-img" />
        <view class="info">
          <text class="name">{{ item.productName }}</text>
          <text class="spec">{{ item.sku }}</text>
          <text class="price">￥{{ item.price }}</text>
        </view>
        <view class="counter">
          <button
            @click="changeCount('add', idx, -1)"
            :disabled="item.count == 0"
          >
            -
          </button>
          <text>{{ item.count }}</text>
          <button
            @click="changeCount('add', idx, 1)"
            :disabled="item.count >= item.number"
          >
            +
          </button>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="footer">
      <view class="diff-row">
        <text v-if="isCollectOnDelivery == 1">货到付款金额</text>
        <text v-else>差价金额</text>
        <text :class="{ red: diffAmount < 0, green: diffAmount > 0 }">
          ￥{{ diffAmount.toFixed(2) > 0 ? '+' + diffAmount.toFixed(2) : diffAmount.toFixed(2) }}
        </text>
        <button class="footer-btn" @click="footerAction(diffAction)">
          {{ diffLabel }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { getOrderDetail, getStockUpDetails ,personnelAdjustOrder } from "@/api/index.js";
export default {
  data() {
    return {
      orderNo: "",
      orderInfo: {},
      addList: [],
      originalList: [],
      defaultImg: "/static/default.png",
      diffAmount: 0,
      diffLabel: "确认调整",
      diffAction: "confirm",
      initialTotal: 0, // 新增：记录最初原始商品总价
      isCollectOnDelivery: 0,
    };
  },
  onLoad(options) {
    if (!options.orderNo)
      return uni.showToast({ title: "缺少参数", icon: "none" });
    this.orderNo = options.orderNo;
    this.getOrderInfo();
    this.isCollectOnDelivery = options.isCollectOnDelivery;
  },
  methods: {
    getOrderInfo() {
      uni.showLoading({ title: "正在加载中" });
      getStockUpDetails(this.orderNo)
        .then((res) => {
          uni.hideLoading();
          let data = res.data;
          this.orderInfo = data;
          console.log(this.orderInfo,109);
          this.addList = (data.addList || []).map((i) => ({
            ...i,
            count: 0,
          }));
          this.originalList = (data.originalList || []).map((i) => ({
            ...i,
            count: i.number || 1,
            initCount: i.number || 1, // 记录初始数量
          }));
          // 记录初始原始商品总价
          this.initialTotal = this.originalList.reduce((sum, item) => sum + Number(item.price) * (item.count || 0), 0);
          this.calcDiff();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getAdjustParams() {
      // addList: 补充商品数量 > 0
      const addList = this.addList
        .filter(item => item.count > 0)
        .map(item => ({
          shopSpecId: item.productAttrValueId,
          number: item.count
        }));
      // removeList: 原始商品数量减少
      const removeList = this.originalList
        .filter(item => item.count < item.initCount)
        .map(item => ({
          shopSpecId: item.productAttrValueId,
          number: item.initCount - item.count
        }));
      return {
        productAttrAdjustRequest: {
          addList,
          removeList,
          orderNo: this.orderNo,
          frontPrice: this.diffAmount
        }
      };
    },
    async footerAction(action) {
      // 新增：判断原始商品是否全部为0
   
      // 组装参数并调用接口
      let  params = this.getAdjustParams();
      const allOriginalZero = this.originalList.every(item => item.count === 0);
      if (allOriginalZero && params.productAttrAdjustRequest.addList.length === 0) {
        uni.showToast({ title: '商品不能为0，请用户拒绝签收', icon: 'none' });
        return;
      }
      try {
        uni.showLoading({ title: '提交中...' });
        const res = await personnelAdjustOrder(params.productAttrAdjustRequest);
        uni.hideLoading();
        uni.showToast({ title: '操作成功', icon: 'success' });
		// uni.navigateBack();
		    uni.redirectTo({
			    url: '/pages/orderManageRider/orderManageRider?orderNo=' + this.orderNo
		    })
      } catch (e) {
        uni.hideLoading();
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    },
    changeCount(type, idx, delta) {
      let list = type === "original" ? this.originalList : this.addList;
      let item = list[idx];
      let newCount = item.count + delta;
      if (newCount < 0 || newCount > item.number) return;
      this.$set(list, idx, { ...item, count: newCount });
      this.calcDiff();
    },
    calcDiff() {
      // 当前总价 = originalList + addList
      const currentTotal =
        this.originalList.reduce((sum, item) => sum + Number(item.price) * (item.count || 0), 0) +
        this.addList.reduce((sum, item) => sum + Number(item.price) * (item.count || 0), 0);
        let diff = 0;
        if(this.isCollectOnDelivery == 1){
          //货到付款就是所有商品的价格
          diff =  currentTotal;
        }else{
          //其他情况就是原始商品支付的价格 减去 添加或减少商品总价
          diff = currentTotal - this.initialTotal;
        }
      this.diffAmount = diff;
      if (diff > 0) {
        this.diffLabel = "补差价";
        this.diffAction = "pay";
      } else if (diff < 0) {
        this.diffLabel = "退差价";
        this.diffAction = "refund";
      } else {
        this.diffLabel = "确认调整";
        this.diffAction = "confirm";
      }
    },
    goBack() {
      uni.navigateBack();
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
}
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #0066e6;
  color: #fff;
  height: 90rpx;
  padding: 0 30rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
}
.back,
.help {
  font-size: 32rpx;
}
.section {
  margin: 30rpx 0 0 0;
}
.section-title {
  color: #aaa;
  font-size: 26rpx;
  margin-left: 30rpx;
}
.card {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 20rpx;
  margin: 20rpx 30rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx #eee;
}
.product-img {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  background: #eee;
}
.info {
  flex: 1;
  margin-left: 20rpx;
}
.name {
  font-size: 30rpx;
  font-weight: bold;
}
.spec {
  color: #888;
  font-size: 24rpx;
  margin: 0 10rpx;
}
.price {
  color: #e60012;
  font-size: 28rpx;
}
.counter {
  display: flex;
  align-items: center;
}
.counter button {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #f0f0f0;
  border: none;
  font-size: 32rpx;
  margin: 0 10rpx;
}
.counter text {
  width: 40rpx;
  text-align: center;
}
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -2rpx 8rpx #eee;
  padding: 20rpx 0;
}
.diff-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10rpx 30rpx;
}
.footer-btn {
  background: #0066e6;
  color: #fff;
  border-radius: 30rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
  border: none;
}
.red {
  color: #e60012;
}
.green {
  color: #09bb07;
}
</style>
